//
//  NetworkTool.m
//  DaiShengInvest
//
//  Created by 张睿 on 2017/7/12.
//  Copyright © 2017年 davinci. All rights reserved.
//

#import "NetworkTool.h"

@implementation NetworkTool

/** 单例 实例化 */
+ (instancetype)shareManager{
    
    static NetworkTool *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
//        NSData * cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
//        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
//        [defaults setObject: cookiesData forKey:@"mUserDefaultsCookie"];
//        [defaults synchronize];
//        
//        NSArray * cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey:@"mUserDefaultsCookie"]];
//        NSHTTPCookieStorage * cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//        for (NSHTTPCookie * cookie in cookies){
//            [cookieStorage setCookie: cookie];
//        }
        
        // 创建可变字典用于存放Cookie
//        NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
//        
//        // 存放新添加的cookie
//#warning 单个的Cookie还好，但是楼主在工厂类方法中拼接了一个包含6个设备信息的value值，最后忘记加分号了，测试也没测出来
//#warning 因为不影响功能，但是后面的cookie就自动拼接上了，H5那边也识别不到，险造成重大事故(涉及金融。。)，望后来者看到，提前做好准备(就凭这个坑，你得给我个赞)
//        NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
//        
//        // 获取
//        NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//        
//        for (NSHTTPCookie *cookie in [cookieJar cookies]) {
//            [cookieDic setObject:cookie.value forKey:cookie.name];
//        }
//        
//        // cookie重复，先放到字典去重，再进行拼接
//        for (NSString *key in cookieDic) {
//            NSString *appendString = [NSString stringWithFormat:@"%@=%@", key, [cookieDic valueForKey:key]];
//            [cookieValue appendString:appendString];
//        }
//        
//        
//        NSLog(@"111==%@",cookieValue);
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURL * url = [NSURL URLWithString:@"http://api.xianjinedai.com/"];
//        NSURL * url = [NSURL URLWithString:@"http://106.14.157.18:8080/"];

        //1.实例化
        instance = [[NetworkTool alloc] initWithBaseURL:url sessionConfiguration:configuration];

        //2.可接受格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
        //3.请求格式（默认：二进制）
//        instance.requestSerializer = [AFJSONRequestSerializer serializer];
//        instance.responseSerializer = [AFHTTPResponseSerializer serializer];

        
        //4.超时
        instance.requestSerializer.timeoutInterval = 60.0;
        
        
       //        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
//        instance.requestSerializer = [AFHTTPRequestSerializer serializer];
//        
//            NSLog(@"==%@",cookieValue);
//        [instance.requestSerializer setValue:cookieValue forHTTPHeaderField:@"Cookie"];
    });
    NSString * token = DEF_GET_OBJECT(userToken);
//            NSLog(@"token==%@",token);
    
    if ([token isEqualToString:@""]) {
        
        
    }else{
        
        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
        //            instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        [instance.requestSerializer setValue:token forHTTPHeaderField:@"accessToken"];
        
    }

    return instance;
}

//- (BOOL)isReachableByAFN{
//    
//    Reachability *reachability = [Reachability reachabilityWithHostName:CZ_BaseUrl];
//    
//    return reachability.isReachable;
//}


/** 自定义的 GET 请求 */
//- (void)GET_RequestWithUrlString:(NSString *)urlString
//                          parmas:(NSDictionary *)params
//                   successBloock:(SuccessCompletedBlock)success
//                    failureBlock:(FailureCompletedBlock)failure
//               ReachabilityBlock:(ReachabilityIsOKBlock)isReachable{
//    
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//    
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        
//        if (status==AFNetworkReachabilityStatusUnknown || status==AFNetworkReachabilityStatusNotReachable) {
//            
//            isReachable(NO);
//            
//        }else{
//            
//            isReachable(YES);
//            
//            [[NetworkTool shareManager] GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
//                
//                success(responseObject);
//                
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                
//                failure(error);
//                
//            }];
//            
//        }
//    }];
//    
//    
//}
//
///** 自定义的 POST 请求 */
//- (void)POST_RequestWithUrlString:(NSString *)urlString
//                           parmas:(NSDictionary *)params
//                    successBloock:(SuccessCompletedBlock)success
//                     failureBlock:(FailureCompletedBlock)failure
//                ReachabilityBlock:(ReachabilityIsOKBlock)isReachable{
//    
//    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
//    
//    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        
//        if (status==AFNetworkReachabilityStatusUnknown || status==AFNetworkReachabilityStatusNotReachable) {
//            
//            isReachable(NO);
//            
//        }else{
//            
//            isReachable(YES);
//            
//            [[NetworkTool shareManager] POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
//                
//                success(responseObject);
//                
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                
//                failure(error);
//                
//            }];
//        }
//    }];
//}
//
///**  专门为 广告 自定义的 POST 请求 */
//- (void)POST_RequestWithUrlString:(NSString *)urlString
//                           parmas:(NSDictionary *)params
//                    successBloock:(SuccessCompletedBlock)success
//                     failureBlock:(FailureCompletedBlock)failure{
//    
//    
//    [[NetworkTool shareManager] POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) {
//        
//        success(responseObject);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        failure(error);
//        
//    }];
//    
//}


-(void)POST:(NSString *)url Param:(NSDictionary *)param andWaitStr:(NSString *)waitString waitView:(UIView *)waitView success:(void (^)(id _Nullable))success andFailure:(void (^)(NSError * _Nonnull))errorBlock
{

    if(waitView)
    {
        if(waitString && waitString.length){
            [SVProgressHUD showWithStatus:waitString];
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
        }else{
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
            
            [SVProgressHUD show];
        }
    }
    
    [self POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        
//        
//        NSString * string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSError * error;
//        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
        [SVProgressHUD dismiss];
    }];

}



-(void)POSTJson:(NSString *)url Param:(NSDictionary *)param andWaitStr:(NSString *)waitString waitView:(UIView *)waitView success:(void (^)(id _Nullable))success andFailure:(void (^)(NSError * _Nonnull))errorBlock
{
    
    if(waitView)
    {
        if(waitString && waitString.length){
            [SVProgressHUD showWithStatus:waitString];
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
        }else{
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
            
            [SVProgressHUD show];
        }
    }
    self.requestSerializer = [AFJSONRequestSerializer serializer];

    NSString * token = DEF_GET_OBJECT(userToken);
    //        NSLog(@"token==%@",token);
    
    if ([token length]==0) {
        
        
    }else{
        
        self.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
        //            instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        [self.requestSerializer setValue:token forHTTPHeaderField:@"accessToken"];
        
    }

    [self POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        
        //
        //        NSString * string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        //        NSError * error;
        //        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
        [SVProgressHUD dismiss];
    }];
    
}

-(void)GET:(NSString *)url Param:(NSDictionary *)param andWaitStr:(NSString *)waitString waitView:(UIView *)waitView success:(void (^)(id _Nullable))success andFailure:(void (^)(NSError * _Nonnull))errorBlock
{
    if(waitView)
    {
        if(waitString && waitString.length){
            [SVProgressHUD showWithStatus:waitString];
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
        }else{
            [SVProgressHUD appearance].defaultStyle = SVProgressHUDStyleLight;
            [[SVProgressHUD appearance] setDefaultMaskType:SVProgressHUDMaskTypeClear];
            
            [SVProgressHUD show];
        }
    }
    
    [self GET:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        
//        
//        NSString * string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSError * error;
//        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        errorBlock(error);
        [SVProgressHUD dismiss];
    }];

}


-(void)POST:(NSString*)url Param:(NSDictionary*)param File:(NSData*)file fileKey:(NSString*)fileKey andFileName:(NSString*)fileName andWaitStr:(NSString*)waitString waitView:(UIView*)waitView success:(void(^)(id _Nullable responseObject))success andFailure:(void(^)(NSError * _Nonnull error))errorBlock
{

    MBProgressHUD *hud;
    if(waitView)
    {
        if(waitString && waitString.length){
            hud = [MBProgressHUD showHUDAddedTo:waitView animated:YES];
            hud.userInteractionEnabled = NO;
            // Configure for text only and offset down
            hud.mode = MBProgressHUDModeIndeterminate;
            hud.yOffset = -100;
            hud.labelText = waitString;
            hud.opacity =  0.7;
            hud.removeFromSuperViewOnHide = YES;
        }else{
            hud = [MBProgressHUD showHUDAddedTo:waitView animated:YES];
            hud.userInteractionEnabled = NO;
            hud.yOffset = -100;
            // Configure for text only and offset down
            hud.mode = MBProgressHUDModeIndeterminate;
            hud.opacity =  0.7;
            hud.removeFromSuperViewOnHide = YES;
        }
    }
    [self POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:file name:fileKey fileName:fileName mimeType:@"image/jpg"];
        
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        hud.progress = uploadProgress.fractionCompleted;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:YES];
        
       
        
        success(responseObject);
        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hide:YES];
        errorBlock(error);
    }];
}







+(instancetype)manager
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURL * url = [NSURL URLWithString:@"http://api.xianjinedai.com/"];
//    NSURL * url = [NSURL URLWithString:@"http://106.14.157.18:8080/"];
    //1.实例化
    NetworkTool*instance = [[NetworkTool alloc] initWithBaseURL:url sessionConfiguration:configuration];
    
    //2.可接受格式
    instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
    //3.请求格式（默认：二进制）
    //        instance.requestSerializer = [AFJSONRequestSerializer serializer];
    //        instance.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    //4.超时
    instance.requestSerializer.timeoutInterval = 60.0;
    
    
    NSString * token = DEF_GET_OBJECT(userToken);
    //        NSLog(@"token==%@",token);
    
    if ([token length]==0) {
        
        
    }else{
        
        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
        //            instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        [instance.requestSerializer setValue:token forHTTPHeaderField:@"accessToken"];
        
    }
    return instance;
}








@end
